package cn.tiger.controller;

import cn.tiger.common.Result;
import cn.tiger.pojo.domain.Membership;
import cn.tiger.pojo.domain.User;
import cn.tiger.pojo.dto.MembershipRechargeRequest;
import cn.tiger.pojo.vo.MembershipVO;
import cn.tiger.repository.ConversationRepository;
import cn.tiger.service.MembershipService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 会员控制器
 * 
 * 提供会员管理相关的REST API接口，包括充值、状态查询、充值记录等功能
 * 支持用户会员权限管理和限制检查
 * 
 * @author AI Backend Team
 * @version 1.0
 * @since 2025-09-26
 */
@Slf4j
@RestController
@RequestMapping("/api/membership")
@RequiredArgsConstructor
@Validated
@Tag(name = "会员管理", description = "会员充值、状态查询相关接口")
public class MembershipController {
    
    private final MembershipService membershipService;
    private final ConversationRepository conversationRepository;
    
    /**
     * 充值会员
     * @param request 充值请求
     * @param httpRequest HTTP请求对象，用于获取用户信息
     * @return 充值结果
     */
    @Operation(summary = "充值会员", description = "用户充值VIP会员")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "充值成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @PostMapping("/recharge")
    public Result<Long> rechargeMembership(@Valid @RequestBody MembershipRechargeRequest request, 
                                         HttpServletRequest httpRequest) {
        try {
            // 从JWT token中获取用户ID
            Long userId = (Long) httpRequest.getAttribute("userId");
            
            Long recordId = membershipService.rechargeMembership(userId, request.getAmount(), request.getMonths());
            return Result.success("充值成功", recordId);
        } catch (Exception e) {
            log.error("充值会员失败", e);
            return Result.error(new cn.tiger.common.CodeMsg(500, e.getMessage()));
        }
    }
    
    /**
     * 获取用户会员信息
     * @param httpRequest HTTP请求对象，用于获取用户信息
     * @return 会员信息
     */
    @Operation(summary = "获取会员信息", description = "获取当前用户的会员状态和限制信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @GetMapping("/info")
    public Result<MembershipVO> getMembershipInfo(HttpServletRequest httpRequest) {
        try {
            // 从JWT token中获取用户ID
            Long userId = (Long) httpRequest.getAttribute("userId");
            
            User user = membershipService.getUserMembershipInfo(userId);
            boolean isVip = membershipService.isVipMember(userId);
            
            // 获取当前对话数量
            long currentConversations = conversationRepository.countByUserIdAndStatus(userId, (byte) 1);
            
            MembershipVO vo = new MembershipVO();
            vo.setMembershipType(user.getMembershipType());
            vo.setIsVip(isVip);
            vo.setExpireTime(user.getMembershipExpireTime());
            vo.setCurrentConversations(currentConversations);
            
            if (isVip) {
                // VIP用户无限制
                vo.setMaxConversations(-1); // -1表示无限制
                vo.setMaxMessagesPerConversation(-1);
                vo.setCanCreateConversation(true);
                
                // 计算剩余天数
                if (user.getMembershipExpireTime() != null) {
                    long remainingDays = ChronoUnit.DAYS.between(LocalDateTime.now(), user.getMembershipExpireTime());
                    vo.setRemainingDays(Math.max(0, remainingDays));
                }
            } else {
                // 免费用户限制
                vo.setMaxConversations(MembershipService.FREE_MAX_CONVERSATIONS);
                vo.setMaxMessagesPerConversation(MembershipService.FREE_MAX_MESSAGES_PER_CONVERSATION);
                vo.setCanCreateConversation(membershipService.canCreateConversation(userId, currentConversations));
                vo.setRemainingDays(null);
            }
            
            return Result.success("获取会员信息成功", vo);
        } catch (Exception e) {
            log.error("获取会员信息失败", e);
            return Result.defaultError();
        }
    }
    
    /**
     * 获取用户充值记录
     * @param httpRequest HTTP请求对象，用于获取用户信息
     * @return 充值记录列表
     */
    @Operation(summary = "获取充值记录", description = "获取当前用户的所有充值记录")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @GetMapping("/records")
    public Result<List<Membership>> getMembershipRecords(HttpServletRequest httpRequest) {
        try {
            // 从JWT token中获取用户ID
            Long userId = (Long) httpRequest.getAttribute("userId");
            
            List<Membership> records = membershipService.getUserMembershipRecords(userId);
            return Result.success("获取充值记录成功", records);
        } catch (Exception e) {
            log.error("获取充值记录失败", e);
            return Result.defaultError();
        }
    }
    
    /**
     * 检查是否可以创建对话
     * @param httpRequest HTTP请求对象，用于获取用户信息
     * @return 检查结果
     */
    @Operation(summary = "检查创建对话权限", description = "检查当前用户是否可以创建新对话")
    @GetMapping("/check/conversation")
    public Result<Boolean> checkCanCreateConversation(HttpServletRequest httpRequest) {
        try {
            // 从JWT token中获取用户ID
            Long userId = (Long) httpRequest.getAttribute("userId");
            
            long currentConversations = conversationRepository.countByUserIdAndStatus(userId, (byte) 1);
            boolean canCreate = membershipService.canCreateConversation(userId, currentConversations);
            
            return Result.success("检查完成", canCreate);
        } catch (Exception e) {
            log.error("检查创建对话权限失败", e);
            return Result.defaultError();
        }
    }
}